"use client"

import React, { SVGProps, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Time } from "@internationalized/date";
import {
  TableHeader,
  TableColumn,
  TableBody,
  TableRow,
  TableCell,
  Input,
  Button,
  DropdownTrigger,
  Dropdown,
  DropdownMenu,
  DropdownItem,
  Pagination,
  Selection,
  SortDescriptor,
  Table,
  useDisclosure,
} from "@nextui-org/react";
import { ReportType, XingHaoType } from "@/type/report";
import DataModal from "../DataModal";
import { deleteReport } from "@/api/team/delete";
import toast from "react-hot-toast";
import { getReportData } from "@/api/team/report";
import { useAppDispatch, useAppSelector } from "@/lib/hooks";
import { deleteById, selectReport, setReportData } from "@/lib/features/report/reportSlice";
import { STATUS } from "../Report";

export type IconSvgProps = SVGProps<SVGSVGElement> & {
  size?: number;
};

export function capitalize(s: string) {
  return s ? s.charAt(0).toUpperCase() + s.slice(1).toLowerCase() : "";
}

export const PlusIcon = ({ size = 24, width, height, ...props }: IconSvgProps) => {
  return (
    <svg
      aria-hidden="true"
      fill="none"
      focusable="false"
      height={size || height}
      role="presentation"
      viewBox="0 0 24 24"
      width={size || width}
      {...props}
    >
      <g
        fill="none"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={1.5}
      >
        <path d="M6 12h12" />
        <path d="M12 18V6" />
      </g>
    </svg>
  );
};

export const VerticalDotsIcon = ({ size = 24, width, height, ...props }: IconSvgProps) => {
  return (
    <svg
      aria-hidden="true"
      fill="none"
      focusable="false"
      height={size || height}
      role="presentation"
      viewBox="0 0 24 24"
      width={size || width}
      {...props}
    >
      <path
        d="M12 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 12c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"
        fill="currentColor"
      />
    </svg>
  );
};

export const SearchIcon = (props: IconSvgProps) => {
  return (
    <svg
      aria-hidden="true"
      fill="none"
      focusable="false"
      height="1em"
      role="presentation"
      viewBox="0 0 24 24"
      width="1em"
      {...props}
    >
      <path
        d="M11.5 21C16.7467 21 21 16.7467 21 11.5C21 6.25329 16.7467 2 11.5 2C6.25329 2 2 6.25329 2 11.5C2 16.7467 6.25329 21 11.5 21Z"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth="2"
      />
      <path
        d="M22 22L20 20"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth="2"
      />
    </svg>
  );
};

export const EyeIcon = (props: IconSvgProps) => {
  return (
    <svg
      aria-hidden="true"
      fill="none"
      focusable="false"
      height="1em"
      role="presentation"
      viewBox="0 0 20 20"
      width="1em"
      {...props}
    >
      <path
        d="M12.9833 10C12.9833 11.65 11.65 12.9833 10 12.9833C8.35 12.9833 7.01666 11.65 7.01666 10C7.01666 8.35 8.35 7.01666 10 7.01666C11.65 7.01666 12.9833 8.35 12.9833 10Z"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={1.5}
      />
      <path
        d="M9.99999 16.8916C12.9417 16.8916 15.6833 15.1583 17.5917 12.1583C18.3417 10.9833 18.3417 9.00831 17.5917 7.83331C15.6833 4.83331 12.9417 3.09998 9.99999 3.09998C7.05833 3.09998 4.31666 4.83331 2.40833 7.83331C1.65833 9.00831 1.65833 10.9833 2.40833 12.1583C4.31666 15.1583 7.05833 16.8916 9.99999 16.8916Z"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={1.5}
      />
    </svg>
  );
};

export const DeleteIcon = (props: IconSvgProps) => {
  return (
    <svg
      aria-hidden="true"
      fill="none"
      focusable="false"
      height="1em"
      role="presentation"
      viewBox="0 0 20 20"
      width="1em"
      {...props}
    >
      <path
        d="M17.5 4.98332C14.725 4.70832 11.9333 4.56665 9.15 4.56665C7.5 4.56665 5.85 4.64998 4.2 4.81665L2.5 4.98332"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={1.5}
      />
      <path
        d="M7.08331 4.14169L7.26665 3.05002C7.39998 2.25835 7.49998 1.66669 8.90831 1.66669H11.0916C12.5 1.66669 12.6083 2.29169 12.7333 3.05835L12.9166 4.14169"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={1.5}
      />
      <path
        d="M15.7084 7.61664L15.1667 16.0083C15.075 17.3166 15 18.3333 12.675 18.3333H7.32502C5.00002 18.3333 4.92502 17.3166 4.83335 16.0083L4.29169 7.61664"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={1.5}
      />
      <path
        d="M8.60834 13.75H11.3833"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={1.5}
      />
      <path
        d="M7.91669 10.4167H12.0834"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={1.5}
      />
    </svg>
  );
};

export const EditIcon = (props: IconSvgProps) => {
  return (
    <svg
      aria-hidden="true"
      fill="none"
      focusable="false"
      height="1em"
      role="presentation"
      viewBox="0 0 20 20"
      width="1em"
      {...props}
    >
      <path
        d="M11.05 3.00002L4.20835 10.2417C3.95002 10.5167 3.70002 11.0584 3.65002 11.4334L3.34169 14.1334C3.23335 15.1084 3.93335 15.775 4.90002 15.6084L7.58335 15.15C7.95835 15.0834 8.48335 14.8084 8.74168 14.525L15.5834 7.28335C16.7667 6.03335 17.3 4.60835 15.4583 2.86668C13.625 1.14168 12.2334 1.75002 11.05 3.00002Z"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeMiterlimit={10}
        strokeWidth={1.5}
      />
      <path
        d="M9.90833 4.20831C10.2667 6.50831 12.1333 8.26665 14.45 8.49998"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeMiterlimit={10}
        strokeWidth={1.5}
      />
      <path
        d="M2.5 18.3333H17.5"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeMiterlimit={10}
        strokeWidth={1.5}
      />
    </svg>
  );
};

export const ChevronDownIcon = ({ strokeWidth = 1.5, ...otherProps }: IconSvgProps) => {
  return (
    <svg
      aria-hidden="true"
      fill="none"
      focusable="false"
      height="1em"
      role="presentation"
      viewBox="0 0 24 24"
      width="1em"
      {...otherProps}
    >
      <path
        d="m19.92 8.95-6.52 6.52c-.77.77-2.03.77-2.8 0L4.08 8.95"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeMiterlimit={10}
        strokeWidth={strokeWidth}
      />
    </svg>
  );
};

export const columns = [
  { name: "优先顺序", uid: "id" },
  { name: "产品项目", uid: "cpxm", sortable: true },
  { name: "节拍时间", uid: "jpsj", sortable: true },
  { name: "开始时间", uid: "kssj", sortable: true },
  { name: "结束时间", uid: "jssj" },
  { name: "连班", uid: "lb" },
  { name: "生产工时", uid: "scgs", sortable: true },
  { name: "5S收线", uid: "wssx" },
  { name: "投入台架", uid: "trtj", sortable: true },
  { name: "理论产能", uid: "llcn", sortable: true },
  { name: "生产效率", uid: "scxl", sortable: true },
  { name: "计划数量", uid: "jhsl", sortable: true },
  { name: "实际完成", uid: "sjwc", sortable: true },
  { name: "型号", uid: "xh", sortable: true },
  { name: "完成率/%", uid: "wcl", sortable: true },
  { name: "不良数", uid: "bls", sortable: true },
  { name: "投入人员", uid: "trry", sortable: true },
  { name: "停机时间", uid: "tjsj", sortable: true },
  { name: "操作员", uid: "czy", sortable: true },
  { name: "备注", uid: "bz", sortable: true },
  { name: "Actions", uid: "actions" },
];

const INITIAL_VISIBLE_COLUMNS = ["id", "cpxm", "jpsj", "actions"];


export const statusOptions = [
  { name: "Actions", uid: "actions" },
  { name: "优先顺序", uid: "id" },
  { name: "产品项目", uid: "cpxm" },
  { name: "节拍时间", uid: "jpsj" },
  { name: "开始时间", uid: "kssj" },
  { name: "结束时间", uid: "jssj" },
  { name: "连班", uid: "lb" },
  { name: "生产工时", uid: "scgs" },
  { name: "5S收线", uid: "wssx" },
  { name: "投入台架", uid: "trtj" },
  { name: "理论产能", uid: "llcn" },
  { name: "生产效率", uid: "scxl" },
  { name: "计划数量", uid: "jhsl" },
  { name: "实际完成", uid: "sjwc" },
  { name: "型号", uid: "xh" },
  { name: "完成率/%", uid: "wcl" },
  { name: "不良数", uid: "bls" },
  { name: "投入人员", uid: "trry" },
  { name: "停机时间", uid: "tjsj" },
  { name: "操作员", uid: "czy" },
  { name: "备注", uid: "bz" },
];




export default function TableView({ menuChange, team_id, dtId }: { menuChange: (v: STATUS) => void, team_id: number, dtId: number }) {
  const [filterValue, setFilterValue] = React.useState("");
  const [selectedKeys, setSelectedKeys] = React.useState<Selection>(new Set([]));
  const { isOpen, onOpen, onClose } = useDisclosure();
  const [visibleColumns, setVisibleColumns] = React.useState<Selection>(
    new Set(INITIAL_VISIBLE_COLUMNS),
  );
  const [dataDetail, setDataDetail] = useState<ReportType | null>(null)
  const action = useRef<number>(1)
  // const [statusFilter, setStatusFilter] = React.useState<Selection>("all");
  const [rowsPerPage, setRowsPerPage] = React.useState(5);
  const [sortDescriptor, setSortDescriptor] = React.useState<SortDescriptor>({
    column: "id",
    direction: "ascending",
  });

  const dispatch = useAppDispatch();

  const data = useAppSelector(selectReport) ?? []

  type RowTemp = (typeof data)[0];


  const [page, setPage] = React.useState(1);

  const hasSearchFilter = Boolean(filterValue);

  const headerColumns = React.useMemo(() => {
    if (visibleColumns === "all") return columns;

    return columns.filter((column) => Array.from(visibleColumns).includes(column.uid));
  }, [visibleColumns]);

  const filteredItems = React.useMemo(() => {
    let filteredUsers = [...data];

    if (hasSearchFilter) {
      filteredUsers = filteredUsers.filter((user) =>
        user.czy.toLowerCase().includes(filterValue.toLowerCase()),
      );
    }

    filteredUsers = filteredUsers.filter((user) => {
      return user.sort == dtId
    })
    // 状态过滤
    // if (statusFilter !== "all" && Array.from(statusFilter).length !== statusOptions.length) {
    //   filteredUsers = filteredUsers.filter((user) => {
    //     console.log(Array.from(statusFilter).includes(Object.keys(user)[0]));
    //     return Array.from(statusFilter).includes(Object.keys(user)[0])
    //   });
    // }

    return filteredUsers;
    // statusFilter
  }, [data, filterValue]);

  const pages = Math.ceil(filteredItems.length / rowsPerPage);

  const items = React.useMemo(() => {
    const start = (page - 1) * rowsPerPage;
    const end = start + rowsPerPage;

    return filteredItems.slice(start, end);
  }, [page, filteredItems, rowsPerPage]);

  const sortedItems = React.useMemo(() => {
    return [...items].sort((a: RowTemp, b: RowTemp) => {
      const first = a[sortDescriptor.column as keyof RowTemp] as number;
      const second = b[sortDescriptor.column as keyof RowTemp] as number;
      const cmp = first < second ? -1 : first > second ? 1 : 0;

      return sortDescriptor.direction === "descending" ? -cmp : cmp;
    });
  }, [sortDescriptor, items]);

  const renderCell = useCallback((user: RowTemp, columnKey: React.Key) => {
    const cellValue = user[columnKey as keyof RowTemp];

    switch (columnKey) {
      case "id":
        return (
          <span className="text-sm">{user.tjbh}#</span>
        );
      case "cpxm":
        return (
          <span className="text-sm">{user.cpxm}</span>
        );
      case "jpsj":
        return (
          <span className="text-sm">{user.jpsj}</span>
        );
      case "kssj":
        return (
          <span className="text-sm">{user.kssj}</span>
        );
      case "jssj":
        return (
          <span className="text-sm">{user.jssj}</span>
        );
      case "lb":
        return (
          <span className="text-sm">{user.lb}</span>
        );
      case "scgs":
        return (
          <span className="text-sm">{user.scgs}</span>
        );
      case "wssx":
        return (
          <span className="text-sm">{user.wssx}</span>
        );
      case "yxgs":
        return (
          <span className="text-sm">{user.yxgs}</span>
        );
      case "trtj":
        return (
          <span className="text-sm">{user.trtj}</span>
        );
      case "llcn":
        return (
          <span className="text-sm">{user.llcn}</span>
        );
      case "scxl":
        return (
          <span className="text-sm">{user.scxl}</span>
        );
      case "jhsl":
        return (
          <span className="text-sm">{user.jhsl}</span>
        );
      case "sjwc":
        return (
          <span className="text-sm">{user.sjwc}</span>
        );
      case "xh":
        const result: XingHaoType[] = JSON.parse(user.xh)
        return (
          <pre>
            <code style={{lineHeight: "8px"}} className="text-xs">
              {
                result?.map((item) => {
                  return item.name + "：" + item.price + "\n"
                })
              }
            </code>
          </pre>
        );
      case "wcl":
        return (
          <span className="text-sm">{user.wcl}</span>
        );
      case "bls":
        return (
          <span className="text-sm">{user.bls}</span>
        );
      case "trry":
        return (
          <span className="text-sm">{user.trry}</span>
        );
      case "tjsj":
        return (
          <span className="text-sm">{user.tjsj}</span>
        );
      case "czy":
        return (
          <span className="text-sm">{user.czy}</span>
        );
      case "bz":
        return (
          <span className="text-sm">{user.bz}</span>
        );
      case "actions":
        return (
          <div className="relative text-sm flex justify-end items-center gap-2">
            <Dropdown size="sm" placement="left-start">
              <DropdownTrigger>
                <Button isIconOnly size="sm" variant="light">
                  <VerticalDotsIcon className="text-default-300" />
                </Button>
              </DropdownTrigger>
              <DropdownMenu>
                <DropdownItem key="view" onPress={() => {
                  action.current = 3
                  setDataDetail(user)
                  onOpen()
                }}>
                  <span className="flex items-center text-sm text-default-400 cursor-pointer active:opacity-50">
                    <EyeIcon className="text-default-400 mr-1" /> Details
                  </span>
                </DropdownItem>
                <DropdownItem key="edit" onPress={() => {
                  action.current = 2
                  setDataDetail(user)
                  onOpen()
                }}>
                  <span className="flex items-center text-sm text-default-400 cursor-pointer active:opacity-50">
                    <EditIcon className="text-default-400 mr-1" /> Edit
                  </span>
                </DropdownItem>
                <DropdownItem key="delete" onPress={async () => {
                  if (user.id != undefined && user.id != null && user.id != 0) {
                    const result = await deleteReport(user.id)
                    toast.dismiss()
                    if (result.code == 200) {
                      dispatch(deleteById(user.id))
                      toast.success("删除成功 ✅")
                    } else {
                      toast.error(result.message)
                    }
                  }

                }}>
                  <span className="flex items-center text-sm text-danger cursor-pointer active:opacity-50">
                    <DeleteIcon className="text-danger mr-1" /> Delete
                  </span>
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
        );
      default:
        return cellValue;
    }
  }, []);

  const calcModal = useMemo(() => {
    return (
      <DataModal menuChange={menuChange} team_id={team_id} sort={dtId} data={dataDetail} action={action.current} isOpen={isOpen} onClose={onClose} />
    )
  }, [dataDetail, isOpen, onClose, action.current, dtId, team_id])

  const getData = async () => {
    const result = await getReportData(team_id)
    if (result.code == 200) {
      dispatch(setReportData(result.data.report))
    }

  }

  useEffect(() => {
    getData()
  }, [])

  const onRowsPerPageChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
    setRowsPerPage(Number(e.target.value));
    setPage(1);
  }, []);

  const onSearchChange = useCallback((value?: string) => {
    if (value) {
      setFilterValue(value);
      setPage(1);
    } else {
      setFilterValue("");
    }
  }, []);

  const onClear = useCallback(() => {
    setFilterValue("");
    setPage(1);
  }, []);

  const topContent = useMemo(() => {

    return (
      <div className="flex flex-col gap-4">
        <div className="flex justify-between gap-3 items-end">
          <Input
            isClearable
            size="sm"
            className="min-w-[140px]"
            placeholder="搜索操作员"
            startContent={<SearchIcon />}
            value={filterValue}
            onClear={() => onClear()}
            onValueChange={onSearchChange}
          />
          <div className="flex gap-3">
            {/* <Dropdown size="sm">
              <DropdownTrigger className="flex">
                <Button size="sm" endContent={<ChevronDownIcon className="text-small" />} variant="flat">
                  状态
                </Button>
              </DropdownTrigger>
              <DropdownMenu
                disallowEmptySelection
                aria-label="Table Columns"
                closeOnSelect={false}
                selectedKeys={statusFilter}
                selectionMode="multiple"
                className="max-h-[300px] overflow-auto"
                onSelectionChange={setStatusFilter}
              >
                {statusOptions.map((status) => (
                  <DropdownItem key={status.uid} className="capitalize">
                    {capitalize(status.name)}
                  </DropdownItem>
                ))}
              </DropdownMenu>
            </Dropdown> */}
            <Dropdown>
              <DropdownTrigger className="flex">
                <Button size="sm" endContent={<ChevronDownIcon className="text-small" />} variant="flat">
                  字段
                </Button>
              </DropdownTrigger>
              <DropdownMenu
                disallowEmptySelection
                closeOnSelect={false}
                selectedKeys={visibleColumns}
                className="max-h-[300px] overflow-auto"
                selectionMode="multiple"
                onSelectionChange={setVisibleColumns}
              >

                {columns.map((column) => (
                  <DropdownItem key={column.uid} className="capitalize">
                    {capitalize(column.name)}
                  </DropdownItem>
                ))}
              </DropdownMenu>
            </Dropdown>
            <Button isIconOnly color="primary" size="sm" onPress={() => {
              action.current = 1
              setDataDetail({
                tjbh: data.length + 1,
                cpxm: "0",
                jpsj: 0,
                kssj: new Time(8).toString(),
                jssj: new Time(20).toString(),
                lb: '0',
                scgs: 0,
                wssx: "",
                yxgs: 0,
                llcn: 0,
                trtj: 1,
                scxl: "0",
                jhsl: 0,
                sjwc: 0,
                wcl: "0",
                tjsj: 0,
                bls: 0,
                trry: 1,
                czy: ""
              } as ReportType)
              onOpen()
            }} endContent={<PlusIcon />}>
            </Button>
          </div>
        </div>
      </div >
    );
  }, [
    filterValue,
    // statusFilter,
    visibleColumns,
    onSearchChange,
    onRowsPerPageChange,
    data.length,
    hasSearchFilter,
  ]);

  const bottomContent = React.useMemo(() => {
    return (
      <div className="py-2 px-2 flex justify-center items-center">
        <Pagination
          size="sm"
          isCompact
          showControls
          showShadow
          color="warning"
          page={page}
          total={pages}
          onChange={setPage}
        />
      </div>
    );
  }, [selectedKeys, items.length, page, pages, hasSearchFilter]);

  return (
    <>
      <Table
        isStriped
        isHeaderSticky
        bottomContent={bottomContent}
        selectedKeys={selectedKeys}
        sortDescriptor={sortDescriptor}
        classNames={{
          wrapper: "min-h-[382px]",
        }}
        topContent={topContent}
        topContentPlacement="outside"
        bottomContentPlacement="outside"
        onSelectionChange={setSelectedKeys}
        onSortChange={setSortDescriptor}
        className="box-border"
      >
        <TableHeader columns={headerColumns}>
          {(column) => (
            <TableColumn
              className="min-w-[85px]"
              key={column.uid}
              align={column.uid === "actions" ? "end" : "center"}
              allowsSorting={column.sortable}
            >
              {column.name}
            </TableColumn>
          )}
        </TableHeader>
        <TableBody emptyContent={"没有该条件的数据"} items={sortedItems}>
          {(item) => (
            <TableRow key={item.id}>
              {(columnKey) => <TableCell>{renderCell(item, columnKey)}</TableCell>}
            </TableRow>
          )}
        </TableBody>
      </Table>
      {
        calcModal
      }
    </>
  );
}
